﻿using System;
using System.IO;

namespace AnB.Common
{
    public class PB
    {
        public static object Deserialize(Type type, Stream stream)
        {
            return ProtoBuf.Serializer.NonGeneric.Deserialize(type, stream);
        }
        public static object Deserialize(Type type, byte[] bytes, int index, int count)
        {
            using (var stream = new MemoryStream(bytes, index, count, false))
            {
                return Deserialize(type, stream);
            }
        }
        public static object Deserialize(Type type, byte[] bytes)
        {
            using (var stream = new MemoryStream(bytes, false))
            {
                return Deserialize(type, stream);
            }
        }
        public static T Deserialize<T>(Stream stream)
        {
            return (T)Deserialize(typeof(T), stream);
        }
        public static T Deserialize<T>(byte[] bytes, int index, int count)
        {
            return (T)Deserialize(typeof(T), bytes, index, count);
        }
        public static T Deserialize<T>(byte[] bytes)
        {
            return (T)Deserialize(typeof(T), bytes);
        }
        public static void Serialize(object o, Stream stream)
        {
            ProtoBuf.Serializer.NonGeneric.Serialize(stream, o);
        }

        public static byte[] Serialize(object o)
        {
            using (var stream = new MemoryStream())
            {
                Serialize(o, stream);

                int len = (int)stream.Position;
                stream.Seek(0, SeekOrigin.Begin);
                var bytes = new byte[len];
                stream.Read(bytes, 0, len);

                return bytes;
            }
        }
    }
}
